from transformers import TrainingArguments, Trainer, DataCollatorForSeq2Seq
import os
from peft import PeftModel
from datasets import Dataset
import json
from qwen_vl_utils import process_vision_info
from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
import torch
from peft import LoraConfig, get_peft_model


model_pth = '/home/mbk/lab/aicg/Qwen2.5-VL-7B/Qwen2.5-VL-7B-Instruct'

# 4. validate
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    model_pth,
    torch_dtype=torch.bfloat16,
    device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained(model_pth)
processor = AutoProcessor.from_pretrained(model_pth)


config = LoraConfig(
    task_type="CAUSAL_LM",
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
    inference_mode=False,
    r=64,
    lora_alpha=16,
    lora_dropout=0.05,
    bias="none",
)
peft_model_path = "./output/Qwen2.5-VL-LoRA/checkpoint-10"
val_peft_model = PeftModel.from_pretrained(model, peft_model_path, config=config)

input_content = "陈老师人非常好，做事很细心"

 
def predict(input_content, model):
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": f"<{input_content}> 能证明这句话态度的证据有哪些？请用空格分隔输出"}
            ],
        }
    ]
    text = processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    image_inputs, video_inputs = process_vision_info(messages)
    inputs = processor(
        text=[text],
        images=image_inputs,
        videos=video_inputs,
        padding=True,
        return_tensors="pt",
    )
    inputs = inputs.to(model.device)
 
    generated_ids = model.generate(**inputs, max_new_tokens=128)
    # 取生成的后半部分
    generated_ids_trimmed = [
        out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
    ]
    output_text = processor.batch_decode(
        generated_ids_trimmed,
        skip_special_tokens=True,
        clean_up_tokenization_spaces=False
    )
    return output_text[0]
 
response = predict(input_content, val_peft_model)
print(response)
